package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.adapter.OrderSaleCollectAdapter;
import com.isunland.managesystem.base.BaseConfirmDialogFragment;
import com.isunland.managesystem.base.BaseListFragment;
import com.isunland.managesystem.base.BaseMonthTimeDialogFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.OrderCollectContent;
import com.isunland.managesystem.entity.OrderSaleCollectOriginal;
import com.isunland.managesystem.entity.OrderSaleCollectOriginal.OrderSaleCollectContent;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import org.json.JSONException;

public class OrderSaleCollectFragment extends BaseListFragment {
  protected static final String EXTRA_VLAUE =
      "com.isunland.managesystem.ui.OrderSaleCollectFragment.EXTRA_VLAUE";
  private static final int SEARCH_COLLECT = 0;
  private static final int CHOOSE_MONTH = 1;
  private static final int COUNT = 2;//统计
  private static final int COUNT_SURE = 3;//确定统计

  private ArrayList<OrderSaleCollectContent> mlist;
  private OrderSaleCollectAdapter mAdapter;
  private String collectDate = "";

  private OrderCollectContent collectContent;//查询条件类

  private String startDate = MyDateUtil.getBeforeMonthFirstDay(1);
  private String endDate = MyDateUtil.getBeforeMonthLastDay(1);
  private String statisticType = "01";
  private String statisticTypeName = "出库";
  private String manNameId = "";
  private String manName = "";
  private String customerId = "";
  private String customerName = "";
  private String ifBillAll = "";
  private String ifBillAllName = "";

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setBack(true);
    setTitleCustom(R.string.order_collect_list);
    collectContent =
        new OrderCollectContent(startDate, endDate, statisticType, statisticTypeName, manNameId,
            manName, customerId, customerName, ifBillAll, ifBillAllName);
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_order_collect, menu);
    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
      case android.R.id.home:
        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }
        break;
      //查询
      case R.id.menu_item_query:
        Intent i = new Intent(getActivity(), SearchOrderSaleCollectActivity.class);
        i.putExtra(SearchOrderSaleCollectFragment.EXTRA_VLAUE, collectContent);
        startActivityForResult(i, SEARCH_COLLECT);
        break;
      //统计
      case R.id.menu_item_contract:

        Intent countIntent = new Intent(getActivity(), OrderCountListActivity.class);
        countIntent.putExtra(OrderCountListFragment.EXTRA_VLAUE, collectContent);
        startActivityForResult(countIntent, COUNT);
        break;

      //数据汇总
      case R.id.menu_item_collect:
        //选择汇总月份
        DialogFragment dialog =
            BaseMonthTimeDialogFragment.newInstance(MyDateUtil.getBeforeMonth(1), "请选择要汇总的月份");
        FragmentManager fm = getActivity().getSupportFragmentManager();
        dialog.setTargetFragment(OrderSaleCollectFragment.this, CHOOSE_MONTH);
        dialog.show(fm, "");
        break;

      default:
        break;
    }

    return super.onOptionsItemSelected(item);
  }

  @Override public String getUrl() {

    return ApiConst.ULR_ORDER_COLLECT;
  }

  @Override public HashMap<String, String> getparameters() {
    HashMap<String, String> params = new HashMap<>();
    params.put("curPage", "1");
    params.put("pageSize", "1000");
    params.put("isPaging", "0");//固定值
    params.put("memberCode", mCurrentUser.getMemberCode());
    params.put("statisticType", statisticType);//出入库code,01,02
    params.put("customerId", customerId);//客户或部门
    params.put("beginappDate", startDate);
    params.put("endappDate", endDate);
    params.put("ifBillAll", ifBillAll);//是否全书出入库
    params.put("appManName", manName);//业务员
    params.put("orderField", "order_no");
    params.put("orderSeq", "desc");
    return params;
  }

  @Override public void resolveResponse(String json) {
    OrderSaleCollectOriginal original = new Gson().fromJson(json, OrderSaleCollectOriginal.class);
    ArrayList<OrderSaleCollectContent> rows = original.getRows();
    if (mlist == null) {
      mlist = new ArrayList<>();
    }
    mlist.clear();
    mlist.addAll(rows);
    setAdapter(mlist);
  }

  private void setAdapter(ArrayList<OrderSaleCollectContent> mlist2) {
    if (mAdapter == null) {
      mAdapter = new OrderSaleCollectAdapter(mActivity, mlist2);
    }
    setListAdapter(mAdapter);
    ((OrderSaleCollectAdapter) getListAdapter()).notifyDataSetChanged();
  }

  //出入库单详情界面
  @Override public void onListItemClick(ListView l, View v, int position, long id) {
    OrderSaleCollectContent content = mlist.get(position - 1);
    Intent i = new Intent(getActivity(), DetailOrderColletActivity.class);
    i.putExtra(DetailOrderColletFragment.EXTRA_VLAUE, content);
    i.putExtra(DetailOrderColletFragment.EXTRA_TYPE, statisticType);
    startActivity(i);
    super.onListItemClick(l, v, position, id);
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }

    //查询
    if (requestCode == SEARCH_COLLECT) {
      collectContent = (OrderCollectContent) data.getSerializableExtra(EXTRA_VLAUE);
      getDate(collectContent);
      volleyPost();
    }
    //选择汇总月份
    if (requestCode == CHOOSE_MONTH) {
      Date mdate = (Date) data.getSerializableExtra(BaseMonthTimeDialogFragment.EXTRA_DATE);
      collectDate = MyDateUtil.dateToString(mdate, MyDateUtil.TYPE_MONTH);

      DialogFragment dialog =
          BaseConfirmDialogFragment.newInstance(R.string.order_count_hint, R.string.restart_title);
      FragmentManager fm = getActivity().getSupportFragmentManager();
      dialog.setTargetFragment(OrderSaleCollectFragment.this, COUNT_SURE);
      dialog.show(fm, "");
    }
    if (requestCode == COUNT_SURE) {
      //联网刷新列表，获取汇总月份数据
      volleyPoastGetDate(collectDate);
    }
    super.onActivityResult(requestCode, resultCode, data);
  }

  private void getDate(OrderCollectContent content) {
    startDate = content.getStartDate();//开始时间
    endDate = content.getEndDate();//结束时间
    statisticType = content.getStatisticType();
    statisticTypeName = content.getStatisticTypeName();
    manNameId = content.getManNameId();
    manName = content.getManName();
    customerName = content.getCustomerName();//客户名字
    customerId = content.getCustomerId();//客户id
    ifBillAll = content.getIfBillAll();
    ifBillAllName = content.getIfBillAllName();
  }

  private void volleyPoastGetDate(String collectDate2) {

    String url = ApiConst.getAbsoluteUrl(ApiConst.ULR_COLLECT_DATE);
    HashMap<String, String> params = new HashMap<>();
    params.put("isSearch", "1");
    params.put("memberCode", mCurrentUser.getMemberCode());
    params.put("monthDate", collectDate2);
    params.put("statisticType", statisticType);
    params.put("customerId", customerId);
    params.put("customerName", customerName);
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        MyUtils.dismissDialog();
        OrderSaleCollectOriginal original =
            new Gson().fromJson(arg0, OrderSaleCollectOriginal.class);
        ArrayList<OrderSaleCollectContent> rows = original.getRows();
        if (mlist == null) {
          mlist = new ArrayList<>();
        }
        mlist.clear();
        mlist.addAll(rows);
        setAdapter(mlist);
      }

      @Override public void onVolleyError(VolleyError arg0) {
        ToastUtil.show(R.string.wrong_data);
      }
    });
  }
}
